package pers.whj.net.local.server;

import pers.whj.net.local.protocol.Protocol;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UDPThread extends Thread {
    private final int mServerPort;
    private boolean mEndFlag;
    private DatagramSocket mDS;

    public UDPThread(int serverPort) {
        mServerPort = serverPort;
        init();
    }

    @Override
    public void run() {
        init();
        try {
            mDS = new DatagramSocket(Protocol.PORT_UDP_SERVER);
            byte[] data = new byte[Protocol.LENGTH_READ];
            do {
                DatagramPacket dp = new DatagramPacket(data, data.length);
                mDS.receive(dp);
                deal(mDS, dp);
            } while (!mEndFlag);
            mDS.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void end() {
        mEndFlag = true;
        if (mDS != null) {
            mDS.close();
        }
    }

    private void init() {
        mEndFlag = false;
        mDS = null;
    }

    private void deal(DatagramSocket ds, DatagramPacket dp) {
        byte[] data = dp.getData();
        if (Protocol.getCommand(data) == Protocol.REQ_PORT) {
            try {
                InetSocketAddress address = new InetSocketAddress(dp.getAddress(), dp.getPort());
                data = Protocol.getData(Protocol.RES_PORT, String.valueOf(mServerPort));
                dp = new DatagramPacket(data, 0, data.length, address);
                ds.send(dp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}